﻿using System;
using System.Collections.Generic;
using System.IO;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module.Core.BusinessLogic;
using Module.Core.BusinessLogic.CmsContents;
using Module.Core.Common;
using Module.Core.EntitiesInfo;
using Module.Core.LoginSystem.Commons.Framwork;
using Module.Core.LoginSystem.Components.Roles;
using Module.Core.Utilities;

namespace Web.Cms.Content.Articles
{
    public partial class CreateEditArtiles : AdminUserControl
    {
        #region khai báo biến
        private int contentId = 0;
        private int lang = 1;
        #endregion

        #region PageLoad
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString.Get("contentId") != "")
                {
                    contentId = ObjConvertUtility.ToInt32(Request.QueryString.Get("contentId"));
                }
                else
                {
                    contentId = 0;
                }
                
                if (!Page.IsPostBack)
                {
                    rdtpDistributeOn.SelectedDate = DateTime.Now;
                    // Get permission
                    RolePermisionInfo _roleInfo = RoleController.GetReadWritePermison(CurrentUser.UserID, CurrentCommand.CommandID);
                    if (_roleInfo == null) return;
                    if (_roleInfo.Write == 0)
                    {
                        btnAdd.Visible = false;
                        btnUpdate.Visible = false;
                    }
                    //End

                    //CMSZonesBL.GetSub(DropZone, "0", Const.VN, 0, CurrentUser.UserID);
                    CMSZonesBL.GetDataComboType(DropZone, "0", "(" + ModulType.TinTuc.Type.ToString() + ")");//BinCombo Cateid                       

                    #region Nếu contentId>0 -> gán dữ liệu vào textbox
                    if (contentId > 0)
                    {
                        btnAdd.Visible = false;
                        btnUpdate.Visible = true;
                        CMSContentsInfo info = CMSContentsBL.Select(contentId);
                        if (info != null)
                        {
                            txtHeadline.Text = info.Headline;
                            TxtTeaser.Text = info.Teaser;
                            txtAvatar.Text = info.Avatar;
                            DropZone.SelectedValue = info.ZoneID.ToString();
                            txtAvatarDes.Text = info.AvatarTeaser;
                            rdtpDistributeOn.SelectedDate = info.ModifiedOn;
                            txtBody.Text = info.Body;
                            txtSmallThumbnail.Text = info.SmallAvatar;
                            txtBigThumbnail.Text = info.BigAvatar;
                            txtSubHeadline.Text = info.SubHeadline;
                            dropLang.SelectedValue = info.ToString();
                            txtAttachFile.Text = info.AttachFile;
                            info.Author = "";
                            info.Check_type = 0;
                            SelectedCheckBox(info);
                        }
                    }
                    else
                    {
                        btnAdd.Visible = true;
                        btnUpdate.Visible = false;
                    }
                    #endregion

                    #region Định dạng style CuteEditor
                    if (!Directory.Exists(Server.MapPath("/Uploads/" + CurrentUser.UserID)))
                        Directory.CreateDirectory(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtAttachFile.fpUploadDir = txtBigThumbnail.rootDir = txtSmallThumbnail.rootDir = "/Uploads/" + CurrentUser.UserID;
                    txtAvatar.fpUploadDir = "/Uploads/" + CurrentUser.UserID;
                    //set style for teaser                
                    TxtTeaser.Height = 210;
                    TxtTeaser.Width = 530;
                    TxtTeaser.SetSecurityFilesGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    TxtTeaser.SetSecurityFlashGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    TxtTeaser.SetSecurityGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    TxtTeaser.SetSecurityImageGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    TxtTeaser.SetSecurityMediaGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    TxtTeaser.SetSecurityTemplateGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));

                    txtBody.Height = 400;
                    txtBody.Width = 530;
                    txtBody.SetSecurityFilesGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtBody.SetSecurityFlashGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtBody.SetSecurityGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtBody.SetSecurityImageGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtBody.SetSecurityMediaGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    txtBody.SetSecurityTemplateGalleryPath(Server.MapPath("/Uploads/" + CurrentUser.UserID));
                    #endregion
                }
            }
            catch (Exception ex)
            {
                ltrJump.Text = "Error: " + ex.Message;
            }
        }
        #endregion

        #region showtype
        int ShowType()
        {
            CheckBox[] Boxes = new CheckBox[3];
            Boxes[0] = chTinMoiNhat;
            Boxes[1] = chTinNoiBat;
            Boxes[2] = chTinTieuDiem;
            return ClsCheckBox.ReturnStatusCheck(Boxes);
        }
        #endregion

        #region SelectedCheckBox
        void SelectedCheckBox(CMSContentsInfo info)
        {
            CheckBox[] Boxes = new CheckBox[3];
            Boxes[0] = chTinMoiNhat;
            Boxes[1] = chTinNoiBat;
            Boxes[2] = chTinTieuDiem;


            chTinMoiNhat.Checked = ClsCheckBox.SelectChecked(ClsCheckBox.tinMoiNhat, info.ShowType, Boxes);
            chTinNoiBat.Checked = ClsCheckBox.SelectChecked(ClsCheckBox.tinNoiBat, info.ShowType, Boxes);
            chTinTieuDiem.Checked = ClsCheckBox.SelectChecked(ClsCheckBox.tinTieuDiem, info.ShowType, Boxes);
        }
        #endregion

        #region FillContent
        protected void FillContent(CMSContentsInfo info)
        {
            info.Status = Const.DangSoan;
            info.ContentID = contentId;
            info.ContentVersionID = 0;
            info.VersionID = 1;
            info.Headline = txtHeadline.Text.Trim();
            info.SubHeadline = txtSubHeadline.Text;
            info.KeyContents = ObjMiscUtility.Replace(txtHeadline.Text.Trim());
            info.ZoneID = ObjConvertUtility.ToInt32(DropZone.SelectedValue);
            info.Teaser = TxtTeaser.Text;
            info.AvatarTeaser = txtAvatarDes.Text.Trim();
            info.AttachFile = string.Empty;
            info.Body = txtBody.Text;
            info.ModifiedBy = CurrentUser.UserID;
            info.ModifiedOn = rdtpDistributeOn.SelectedDate;
            info.CreatedOn = rdtpDistributeOn.SelectedDate;
            info.DeletedOn = rdtpDistributeOn.SelectedDate;
            info.DatetimePublish = rdtpDistributeOn.SelectedDate;
            info.DatetimeRemove = rdtpDistributeOn.SelectedDate;
            info.Lang = 1;
            info.Locked = CurrentUser.Username.ToString();
            info.Author = "";
            info.Check_type = 0;
            info.CreatedBy = CurrentUser.UserID;
            info.URL = "";
            info.ShowType = ShowType();

            if (txtAvatar.Text.Trim() != info.Avatar && txtAvatar.Text.Trim().Length > 0)// Nếu thay đổi ảnh -> Thuc hien Crop anh
            {
                info.BigAvatar = ConvertImage.SaveImages(Server.MapPath(txtAvatar.Text.Trim()));
                info.Avatar = ConvertImage.SetAvatarThumbnailWidthDirection(Server.MapPath(txtAvatar.Text.Trim()), 100, "_avatar");
                info.SmallAvatar = ConvertImage.SetAvatarThumbnailWidthDirection(Server.MapPath(txtAvatar.Text.Trim()), 70, "_smallAvatar");
            }
            else
            {
                if (txtAvatar.Text.Length > 0)
                {
                    info.Avatar = txtAvatar.Text.Trim();
                    info.SmallAvatar = txtSmallThumbnail.Text.Trim();
                    info.BigAvatar = txtBigThumbnail.Text.Trim();
                }
                else
                {
                    info.Avatar = "";
                    info.SmallAvatar = "";
                    info.BigAvatar = "";
                }
            }

        }
        #endregion

        #region thêm mới
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                CMSContentsInfo info = new CMSContentsInfo();
                FillContent(info);
                int i = CMSContentsBL.Insert(info);
                if (i > 0)
                {                  
                    Response.Redirect(ObjMiscUtility.GetCPPage("ComposeArticles", new string[] { }, new string[] { }));
                }
            }
            catch (Exception ex)
            {
                ltrJump.Text = "Error: " + ex.Message;
            }
        }
        #endregion

        #region chỉnh sửa
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                CMSContentsInfo info = new CMSContentsInfo();
                FillContent(info);
                CMSContentsBL.Update(info);                
                string nav = Request.QueryString.Get("back");
                if (nav != null)
                    Response.Redirect(HttpUtility.UrlDecode(nav));
                else
                    Response.Redirect(ObjMiscUtility.GetHomeCP());
            }
            catch (Exception ex)
            {
                ltrJump.Text = "Error: " + ex.Message;
            }
        }
        #endregion
    }
}